package com.dataconver.db;

import com.dataconver.config.ConfigManager;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import jakarta.annotation.PostConstruct;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 数据库连接管理器
 * 使用HikariCP连接池管理SQLServer和MySQL连接
 * 支持Spring Boot注入和传统静态方法两种方式
 */
@Component
public class DatabaseManager {
    private static final Logger logger = LoggerFactory.getLogger(DatabaseManager.class);
    
    private static HikariDataSource sqlserverDataSource;
    private static HikariDataSource mysqlDataSource;
    
    // Spring Boot注入的数据源
    @Autowired
    @Qualifier("sqlserverDataSource")
    private DataSource springSqlserverDataSource;
    
    @Autowired
    @Qualifier("mysqlDataSource")
    private DataSource springMysqlDataSource;
    
    @PostConstruct
    public void init() {
        // 如果Spring Boot数据源可用，则使用它们
        if (springSqlserverDataSource != null && springMysqlDataSource != null) {
    
            // 将Spring Boot数据源转换为HikariDataSource以保持兼容性
            if (springSqlserverDataSource instanceof HikariDataSource) {
                sqlserverDataSource = (HikariDataSource) springSqlserverDataSource;
            }
            if (springMysqlDataSource instanceof HikariDataSource) {
                mysqlDataSource = (HikariDataSource) springMysqlDataSource;
            }
        } else {
            // 否则使用传统方式初始化
    
            initializeDataSources();
        }
    }
    
    /**
     * 初始化数据源（传统方式）
     */
    private static void initializeDataSources() {
        try {
            // 初始化SQLServer数据源
            HikariConfig sqlserverConfig = new HikariConfig();
            sqlserverConfig.setDriverClassName(ConfigManager.getString("sqlserver.driver", "com.microsoft.sqlserver.jdbc.SQLServerDriver"));
            sqlserverConfig.setJdbcUrl(ConfigManager.getString("sqlserver.url", ""));
            sqlserverConfig.setUsername(ConfigManager.getString("sqlserver.username", ""));
            sqlserverConfig.setPassword(ConfigManager.getString("sqlserver.password", ""));
            sqlserverConfig.setMaximumPoolSize(ConfigManager.getInt("sqlserver.maxPoolSize", 10));
            sqlserverConfig.setMinimumIdle(ConfigManager.getInt("sqlserver.minIdle", 5));
            sqlserverConfig.setConnectionTimeout(30000);
            sqlserverConfig.setIdleTimeout(600000);
            sqlserverConfig.setMaxLifetime(1800000);
            sqlserverConfig.setPoolName("SQLServer-HikariCP");
            
            sqlserverDataSource = new HikariDataSource(sqlserverConfig);
    
            
            // 初始化MySQL数据源
            HikariConfig mysqlConfig = new HikariConfig();
            mysqlConfig.setDriverClassName(ConfigManager.getString("mysql.driver", "com.mysql.cj.jdbc.Driver"));
            mysqlConfig.setJdbcUrl(ConfigManager.getString("mysql.url", ""));
            mysqlConfig.setUsername(ConfigManager.getString("mysql.username", ""));
            mysqlConfig.setPassword(ConfigManager.getString("mysql.password", ""));
            mysqlConfig.setMaximumPoolSize(ConfigManager.getInt("mysql.maxPoolSize", 10));
            mysqlConfig.setMinimumIdle(ConfigManager.getInt("mysql.minIdle", 5));
            mysqlConfig.setConnectionTimeout(30000);
            mysqlConfig.setIdleTimeout(600000);
            mysqlConfig.setMaxLifetime(1800000);
            mysqlConfig.setPoolName("MySQL-HikariCP");
            
            mysqlDataSource = new HikariDataSource(mysqlConfig);
    
            
        } catch (Exception e) {
            logger.error("初始化数据源失败", e);
            throw new RuntimeException("初始化数据源失败", e);
        }
    }
    
    /**
     * 获取SQLServer连接
     */
    public static Connection getSqlserverConnection() throws SQLException {
        if (sqlserverDataSource == null) {
            throw new SQLException("SQLServer数据源未初始化");
        }
        return sqlserverDataSource.getConnection();
    }
    
    /**
     * 获取MySQL连接
     */
    public static Connection getMysqlConnection() throws SQLException {
        if (mysqlDataSource == null) {
            throw new SQLException("MySQL数据源未初始化");
        }
        return mysqlDataSource.getConnection();
    }
    
    /**
     * 关闭数据源
     */
    public static void closeDataSources() {
        if (sqlserverDataSource != null && !sqlserverDataSource.isClosed()) {
            sqlserverDataSource.close();
        }
        
        if (mysqlDataSource != null && !mysqlDataSource.isClosed()) {
            mysqlDataSource.close();
        }
    }
    
    /**
     * 测试数据库连接
     */
    public static boolean testConnections() {
        try {
            // 测试SQLServer连接
            try (Connection conn = getSqlserverConnection()) {
                // SQLServer连接测试成功
            }
            
            // 测试MySQL连接
            try (Connection conn = getMysqlConnection()) {
                // MySQL连接测试成功
            }
            
            return true;
        } catch (SQLException e) {
            logger.error("❌ 数据库连接测试失败", e);
            return false;
        }
    }
}
